package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.*;

/**
 * https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/description/
 * <p>
 * 给你二叉树的根节点root，返回其节点值自底向上的层序遍历 。
 * <p>
 * 即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历
 * <p>
 * 示例 1：
 * <p>
 * 输入：root = [3,9,20,null,null,15,7]
 * <p>
 * 输出：[[15,7],[9,20],[3]]
 * <p>
 * 示例 2：
 * <p>
 * 输入：root = [1]
 * <p>
 * 输出：[[1]]
 * <p>
 * 示例 3：
 * <p>
 * 输入：root = []
 * <p>
 * 输出：[]
 */
public class _5LetCode107_二叉树的层次遍历II {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        Stack<List<Integer>> stack = new Stack<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                list.add(root.val);
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
            stack.push(list);
        }
        while (!stack.isEmpty()) {
            res.add(stack.pop());
        }
        return res;
    }


    public static void main(String[] args) {
        _5LetCode107_二叉树的层次遍历II sol = new _5LetCode107_二叉树的层次遍历II();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(sol.levelOrderBottom(root));
    }

}
